package com.ethan.lotgateway.netty;

import com.ethan.lotgateway.netty.config.NettyConfig;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class NettyServer  {
    @Autowired
    NettyConfig nettyConfig;
    private NioEventLoopGroup boss;
    private NioEventLoopGroup worker;
    private ServerBootstrap serverBootstrap;
    @Autowired
    ChannelInitHandler channelInitHandler;
    public NettyServer() {
        boss = new NioEventLoopGroup();
        worker = new NioEventLoopGroup();
        serverBootstrap = new ServerBootstrap();

    }
    public void start(int port){
        try{
            serverBootstrap.group(boss,worker).channel(NioServerSocketChannel.class).childHandler(channelInitHandler);
            ChannelFuture sync = serverBootstrap.bind(port).sync();
            sync.channel().closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }

    }

}
